// pages/userManage/index.js
const { userApi, settingsApi } = require("../../utils/api.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 用户列表
    userList: [],
    // 加载状态
    loading: false,
    // 搜索关键词
    searchValue: "",
    // 当前用户信息
    userInfo: null,
    // 是否为管理员
    isAdmin: false,
    // 当前选中的标签
    activeTab: "all",
    // 用户设置
    userSettings: {
      setting2: "",
      setting3: "",
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.checkUserAndLoadData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时刷新数据
    this.loadUserList();
  },

  /**
   * 检查用户身份并加载数据
   */
  checkUserAndLoadData() {
    const userInfo = wx.getStorageSync("userInfo");

    if (!userInfo) {
      wx.showModal({
        title: "需要登录",
        content: "请先登录后再使用此功能",
        showCancel: false,
        confirmText: "去登录",
        success: () => {
          wx.navigateTo({
            url: "/pages/login/index",
          });
        },
      });
      return;
    }

    // 检查是否为管理员
    const isAdmin = userInfo.isAdmin || userInfo.role === "admin";

    if (!isAdmin) {
      wx.showModal({
        title: "权限不足",
        content: "只有管理员才能使用此功能",
        showCancel: false,
        confirmText: "确定",
        success: () => {
          wx.navigateBack();
        },
      });
      return;
    }

    this.setData({
      userInfo: userInfo,
      isAdmin: isAdmin,
    });

    // 加载用户设置
    this.loadUserSettings();

    // 加载用户列表
    this.loadUserList();
  },

  /**
   * 加载用户列表
   */
  async loadUserList() {
    if (this.data.loading) return;

    this.setData({
      loading: true,
    });

    try {
      const result = await userApi.getUserList({
        search: this.data.searchValue,
        page: 1,
        page_size: 100000, // 设置较大的页面大小以获取所有用户
      });

      if (result.code === 0 && result.data) {
        let userList = result.data.list || result.data;

        // 根据当前标签过滤用户
        userList = this.filterUsersByTab(userList);

        this.setData({
          userList: userList,
        });
      } else {
        wx.showToast({
          title: "加载失败",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("加载用户列表失败:", error);
      wx.showToast({
        title: "加载失败，请重试",
        icon: "none",
      });
    } finally {
      this.setData({
        loading: false,
      });
    }
  },

  /**
   * 加载用户设置
   */
  async loadUserSettings() {
    try {
      const result = await settingsApi.getUserSettings();
      if (result.code === 0 && result.data) {
        this.setData({
          userSettings: result.data,
        });
      }
    } catch (error) {
      console.error("加载用户设置失败:", error);
      // 出错时使用默认设置
      this.setData({
        userSettings: {
          setting2: "",
          setting3: "",
        },
      });
    }
  },

  /**
   * 根据标签过滤用户
   */
  filterUsersByTab(userList) {
    const { activeTab } = this.data;

    switch (activeTab) {
      case "normal":
        // 未拉黑的用户
        return userList.filter((user) => !user.is_blacklisted);
      case "blacklisted":
        // 已拉黑的用户
        return userList.filter((user) => user.is_blacklisted);
      case "all":
      default:
        // 全部用户
        return userList;
    }
  },

  /**
   * 搜索输入
   */
  onSearchChange(event) {
    this.setData({
      searchValue: event.detail,
    });
    // 延迟搜索，避免频繁请求
    clearTimeout(this.searchTimer);
    this.searchTimer = setTimeout(() => {
      this.loadUserList();
    }, 500);
  },

  /**
   * 切换标签
   */
  onTabChange(event) {
    const activeTab = event.detail.name;
    this.setData({
      activeTab: activeTab,
    });
    // 重新加载数据
    this.loadUserList();
  },

  /**
   * 拉黑用户
   */
  blacklistUser(event) {
    const userId = event.currentTarget.dataset.userId;
    const user = this.data.userList.find((u) => u.id === userId);

    if (!user) return;

    wx.showModal({
      title: "确认拉黑",
      content: `确定要拉黑用户"${
        user.nickname || user.phone || "未知用户"
      }"吗？拉黑后该用户将无法进行预约。`,
      confirmText: "确认拉黑",
      confirmColor: "#ff4444",
      success: (res) => {
        if (res.confirm) {
          this.updateUserBlacklist(userId, true);
        }
      },
    });
  },

  /**
   * 解除拉黑
   */
  unblacklistUser(event) {
    const userId = event.currentTarget.dataset.userId;
    const user = this.data.userList.find((u) => u.id === userId);

    if (!user) return;

    wx.showModal({
      title: "确认解除拉黑",
      content: `确定要解除用户"${
        user.nickname || user.phone || "未知用户"
      }"的拉黑状态吗？`,
      confirmText: "确认解除",
      success: (res) => {
        if (res.confirm) {
          this.updateUserBlacklist(userId, false);
        }
      },
    });
  },

  /**
   * 更新用户拉黑状态
   */
  async updateUserBlacklist(userId, isBlacklisted) {
    try {
      wx.showLoading({
        title: isBlacklisted ? "拉黑中..." : "解除中...",
      });

      const result = await userApi.updateUserBlacklist(userId, isBlacklisted);

      if (result.code === 0) {
        wx.hideLoading();
        wx.showToast({
          title: isBlacklisted ? "拉黑成功" : "解除成功",
          icon: "success",
        });

        // 重新加载用户列表，确保数据同步
        await this.loadUserList();
      } else {
        throw new Error(result.message || "操作失败");
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || "操作失败，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 切换美甲师状态
   */
  toggleStaffStatus(event) {
    const userId = event.currentTarget.dataset.userId;
    const user = this.data.userList.find((u) => u.id === userId);

    if (!user) return;

    const action = user.is_staff ? "取消美甲师" : "设为美甲师";
    wx.showModal({
      title: `确认${action}`,
      content: `确定要将用户"${
        user.nickname || user.phone || "未知用户"
      }"${action}吗？`,
      confirmText: "确认",
      success: (res) => {
        if (res.confirm) {
          this.updateStaffStatus(userId);
        }
      },
    });
  },

  /**
   * 更新美甲师状态
   */
  async updateStaffStatus(userId) {
    try {
      wx.showLoading({
        title: "更新中...",
      });

      const result = await userApi.toggleStaffStatus(userId);

      if (result.code === 0) {
        wx.hideLoading();
        wx.showToast({
          title: "更新成功",
          icon: "success",
        });

        // 重新加载用户列表，确保数据同步
        await this.loadUserList();
      } else {
        throw new Error(result.message || "操作失败");
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || "操作失败，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 格式化时间显示
   */
  formatTime(timeString) {
    if (!timeString) return "";
    try {
      const date = new Date(timeString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
      return timeString;
    }
  },

  /**
   * 下拉刷新
   */
  async onRefresh() {
    await this.loadUserList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "甲年华美甲美睫 - 管理",
      desc: "管理",
      path: "/pages/userManage/index",
    };
  },
});
